package com.dx.oa.sysmng.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.commons.codec.DecoderException;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dx.oa.framework.util.EncryptUtil;
import com.dx.oa.framework.util.PageUtils;
import com.dx.oa.framework.util.UserUtils;
import com.dx.oa.sysmng.dto.UserDto;
import com.dx.oa.sysmng.dto.UserVo;
import com.dx.oa.sysmng.entity.Role;
import com.dx.oa.sysmng.entity.User;
import com.dx.oa.sysmng.service.IRoleService;
import com.dx.oa.sysmng.service.IUserService;
import com.github.pagehelper.PageInfo;

@Controller
@RequestMapping("/sysmgr/user")
public class UserController {
	
	@Autowired
	private IUserService userService;
	
	@Autowired
	private IRoleService roleService;
//	public IUserService getUserService() {
//		return userService;
//	}
//
//	public void setUserService(IUserService userService) {
//		this.userService = userService;
//	}

	private static Logger logger = Logger.getLogger(UserController.class);

	@RequestMapping("/gotoUserInfo")
	public String gotoUserInfo(Model model)
	{
		List<String> userRoleList = userService.getRoleListStrByUserId(UserUtils.getCurrentUserId());
		StringBuffer userRole = new StringBuffer(userRoleList.get(0));
		for(int i=1; i<userRoleList.size(); i++)
		{
			userRole.append("," + userRoleList.get(i));
		}
		model.addAttribute("userRole", userRole.toString());
		return "sysmanage/user/userInfo";
	}
	
	@RequestMapping("/gotoChangePwd")
	public String gotoChangePwd()
	{
		return "sysmanage/user/changePwd";
	}
	
	//admin 911127
	@RequestMapping("/saveChangePwd")
	public @ResponseBody Map<String,Object> saveChangePwd(String oldPassword, String newPassword, HttpSession session) throws DecoderException
	{
		Map<String,Object> response= new HashMap<String,Object>();
		User nuser = (User)session.getAttribute("user");
		nuser = userService.getUserById(nuser.getUserId());
		session.setAttribute("user", nuser);
		if(nuser == null)
		{
			response.put("result", "更新失败");
		}
		oldPassword = EncryptUtil.transformPsd(oldPassword, nuser.getPassword());
		if(!nuser.getPassword().equals(oldPassword))
		{
			response.put("result", "旧密码错误");
		}
		else
		{
			int userId = nuser.getUserId();
			//System.out.println(userService.getUserById(userId));
			newPassword = EncryptUtil.encryptPwd(newPassword);
			if(userService.updatePwdById(newPassword,userId) > 0)
			{
				response.put("result", "更新成功");
				nuser.setPassword(newPassword);
				session.setAttribute("user", nuser);
			}
			else
				response.put("result", "更新失败");
			
		}
		return response;
		//(EncryptUtil.transformPsd(oldPassword, pwd);
	}
	
	@RequestMapping("/saveSelfUserInfo")
	public @ResponseBody Map<String,String> saveSelfUserInfo(User nowuser,HttpSession session)
	{
		Map<String,String> nmap = new HashMap<String,String>();
		User nuser = (User)session.getAttribute("user");
		int nowid = nuser.getUserId();
		nowuser.setUserId(nowid);
		if(userService.updateUserInfo(nowuser) > 0)
		{
			nmap.put("result", "更新成功");
		//	System.out.println(userService.getUserById(nowid));
			session.setAttribute("user", userService.getUserById(nowid));
		}
		else
		{
			nmap.put("result", "更新失败");
		}
		return nmap;
	}
	
	
	@RequestMapping("/getUserInfoById")
	public @ResponseBody UserDto getUserDtoById(HttpSession session)
	{
		User nuser = (User)session.getAttribute("user");
		int userId = nuser.getUserId();

		UserDto userDto = userService.getUserDtoById((int)userId);
//			$("#deptName").html(data.deptName);  					
//			//表单元素赋值
//			$("#userId").val(data.userId); 
//			$("#loginName").val(data.loginName);
//			$("#userName").val(data.userName);
//			$("#userNo").val(data.userNo);
//			$("#email").val(data.email);
//			$("#phone").val(data.phone);
//			$("#mobile").val(data.mobile);
//			$("#remarks").val(data.remarks);
		System.out.println(userDto);
		return userDto;
	}
	
	
	/**
	 * 用户管理功能
	 */
	@RequestMapping("/gotoUserList")
	public String gotoUserList()
	{
		return "sysmanage/user/userList";
	}
	
	@RequestMapping("/gotoUserEdit")
	public String gotoUserEdit(@ModelAttribute("editFlag") int editFlag,Integer userId,Model model)
	{
		if(2 == editFlag)//添加
		{
			if(userId != null)
			{
				UserDto userDto = userService.getUserDtoById(userId);
				model.addAttribute("userDto", userDto);
				Map<Long,Long> roleCheckMap = new HashMap<Long,Long>();
				List<Long> roleIdList = userService.getRoleListByUserId(userId);
				//System.out.println("roleIdList.size():" + roleIdList.size());
				for(Long roleId:roleIdList)
				{
					//System.out.println(roleId);
					roleCheckMap.put(roleId, roleId);
				}
				model.addAttribute("roleCheckMap", roleCheckMap);
			}
		}
		List<Role> roleList = roleService.getRoleList();
		model.addAttribute("roleList", roleList);
		return "sysmanage/user/userEdit";
	}
	
	@RequestMapping("/getUserList")
	public @ResponseBody Map<String,Object> getUserList(Integer deptId,String userName,Integer pageNo,Integer pageSize)
	{
		System.out.println("getUserList");
		Map<String,Object> resultMap = new HashMap<String,Object>();
		User nuser = new User();
		System.out.println("deptId:" + deptId);
		System.out.println("userName:" + userName);
		nuser.setDeptId(deptId);
		nuser.setUserName(userName);
		PageInfo<UserDto> userInfo = userService.getUserDtoList(nuser ,pageNo, pageSize);
		resultMap.put("userList", userInfo.getList());
		resultMap.put("pageStr", PageUtils.pageStr(userInfo, "userMgr.getUserListPage"));
		return resultMap;
	}
	
	/**
	 * 保存用户信息
	 */
	@RequestMapping("/saveUser")
	public @ResponseBody Map<String,Object> saveUser(@RequestBody UserVo userVo)
	{
		Map<String,Object> resultMap = new HashMap<String,Object>();
		
		try {
			if(userVo != null && userVo.getUser() !=null)
			{
				if(userVo.getUser().getUserId() != null)
				{
					//更新用户
					if(userService.updateUser(userVo))
					{
						resultMap.put("result", "更新用户成功");
					}
					else
					{
						resultMap.put("result", "更新用户失败");
					}
				}
				else
				{
					if(userService.addUser(userVo))
					{
						resultMap.put("result", "新增用户成功");
					}
					else
					{
						resultMap.put("result", "新增用户失败");
					}
					//新增用户
				}
			}
			else
			{
				resultMap.put("result", "操作用户失败");
				logger.error("用户信息有误");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return null;
		}
		return resultMap;
	}
	
	@RequestMapping("/delUser")
	public @ResponseBody Map<String,Object> delUser(Integer userId)
	{
		Map<String,Object> resultMap = new HashMap<String,Object>();
		if(userId != null)
		{
			if(userService.delUser(userId))
			{
				resultMap.put("result", "删除用户成功");
			}
			else
			{
				resultMap.put("result", "删除用户失败");
			}
		}
		else
		{
			resultMap.put("result", "删除用户失败");
		}
		return resultMap;
	}
	
}
